package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.base.shiro.annotion.Permission;
import cn.stylefeng.guns.modular.system.controller.dto.IndentOrderTask;
import cn.stylefeng.guns.modular.system.controller.dto.SendGoodsOrderTask;
import cn.stylefeng.guns.modular.system.entity.*;
import cn.stylefeng.guns.modular.system.model.params.DispatchOrderCheckParam;
import cn.stylefeng.guns.modular.system.model.params.IndentOrderAuditParam;
import cn.stylefeng.guns.modular.system.model.params.paramsDTO.CheckDTO;
import cn.stylefeng.guns.modular.system.service.*;
import cn.stylefeng.guns.modular.system.service.Myservice.DispathService;
import cn.stylefeng.guns.sys.core.StatusCode.DispatchOrderCode;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.SystemConstant;
import cn.stylefeng.guns.sys.core.util.common.ToolUtils;
import cn.stylefeng.guns.sys.core.util.utility.StatusCode;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.data.impl.cachematcher.TasksByExecutionIdMatcher;
import org.activiti.engine.task.Task;
import org.apache.ibatis.annotations.Param;
import org.apache.xmlbeans.impl.regex.REUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 发货单审核表控制器
 *
 * @author ZhangJun
 * @Date 2019-07-04 10:55:34
 */
@Controller
@RequestMapping("/dispatchOrderCheck")
public class DispatchOrderCheckController extends BaseController {

    private String PREFIX = "/dispatchOrderCheck";

    @Autowired
    private DispatchOrderCheckService dispatchOrderCheckService;
    @Autowired
    private AddressRoleService addressRoleService;
    @Autowired
    private DispatchOrderService dispatchOrderService;
    @Autowired
    private CheckLoggingService checkLoggingService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private DispathService dispathService;
    @Autowired
    private UserService userService;
    @Autowired
    private DealerLevelService dealerLevelService;
    @Autowired
    private LevelService levelService;

    @Resource
    private TaskService taskService;
    @Autowired
    private DispatchOrderAuditService dispatchOrderAuditService;
    @Autowired
    private SendGoodsService sendGoodsService;
    @Autowired
    private UserAreaRelationService userAreaRelationService;

    /**
     * 跳转到主页面
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/dispatchOrderCheck.html";
    }

    /**
     * 新增页面
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/dispatchOrderCheck_add.html";
    }

    /**
     * 编辑页面
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/dispatchOrderCheck_edit.html";
    }

    /**
     * 审核页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/checkIndex")
    public String checkIndex(Long id, String taskId) {

        super.setAttr("id", id);
        super.setAttr("taskId", taskId);
        return PREFIX + "/dispatchOrder_check.html";
    }

    /**
     * 退回界面
     *
     * @param id
     * @return
     */
    @RequestMapping("/returnIndex/{id}")
    public String returnIndex(@PathVariable Long id) {
        super.setAttr("id", id);
        return PREFIX + "/dispatchOrder_return.html";
    }

    @RequestMapping("/dispatchDetail")
    public String dispatchDetaiCheck(Long id, String taskId) {
        super.setAttr("id", id);
        super.setAttr("username", ShiroKit.getUserNotNull().getName());
        super.setAttr("deptName", deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        super.setAttr("taskId", taskId);
        return PREFIX + "/dispatchOrder_detail.html";

    }

    /**
     * 发货界面
     *
     * @param id
     * @return
     */
    @RequestMapping("/sendgoods/{id}")
    public String sendgoods(@PathVariable Long id) {
        super.setAttr("id", id);
        super.setAttr("username", ShiroKit.getUserNotNull().getName());
        super.setAttr("deptName", deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/sendgoods.html";
    }


    /**
     * 新增接口
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(DispatchOrderCheckParam dispatchOrderCheckParam) {
        this.dispatchOrderCheckService.add(dispatchOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(DispatchOrderCheckParam dispatchOrderCheckParam) {
        this.dispatchOrderCheckService.update(dispatchOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(DispatchOrderCheckParam dispatchOrderCheckParam) {
        this.dispatchOrderCheckService.delete(dispatchOrderCheckParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(DispatchOrderCheckParam dispatchOrderCheckParam) {
        DispatchOrderCheck detail = this.dispatchOrderCheckService.getById(dispatchOrderCheckParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author ZhangJun
     * @Date 2019-07-04
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(DispatchOrderCheckParam dispatchOrderCheckParam) {
        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(SystemConstant.sendOrder).taskCandidateUser(ShiroKit.getUserNotNull().getId() + "").list();
        if (tasks.size() == 0) {
            return new LayuiPageInfo();
        }
        List<SendGoodsOrderTask> a = new ArrayList<>();
        List<SendGoodsOrderTask> b = new ArrayList<>();
        //找出当前审核人员的区域
        List<UserAreaRelation> userAreaRelations = userAreaRelationService.getBaseMapper().selectList(new QueryWrapper<UserAreaRelation>()
                .lambda().eq(UserAreaRelation::getUserId, ShiroKit.getUserNotNull().getId()));
        if (userAreaRelations != null && userAreaRelations.size() != 0) {
            List<Long> areaIds = userAreaRelations.stream().map(s -> s.getAddressId()).collect(Collectors.toList());

            //根据流程实例ID查询请假申请表单数据
//        if (ShiroKit.hasRole("服务专员")){
            a = tasks.stream().filter(task -> sendGoodsService.getBaseMapper().selectOne(new QueryWrapper<SendGoods>()
                    .lambda().eq(SendGoods::getProcessInstanceId, task.getProcessInstanceId())) != null)
                    .filter(task -> areaIds.contains(getAreaId(task)))
                    .map(task -> {
                        SendGoodsOrderTask sendGoodsOrderTask = new SendGoodsOrderTask();
                        SendGoods sendGoods = sendGoodsService.getBaseMapper().selectOne(new QueryWrapper<SendGoods>()
                                .lambda().eq(SendGoods::getProcessInstanceId, task.getProcessInstanceId()));
                        DispatchOrder dispatchOrder = dispatchOrderService.getById(sendGoods.getDispatchOrderId());
                        sendGoodsOrderTask.setOrderNum(sendGoods.getSendNum());
                        sendGoodsOrderTask.setId(sendGoods.getId());
                        if (ToolUtil.isNotEmpty(dispatchOrder)) {
                            sendGoodsOrderTask.setDealerName(userService.getById(dispatchOrder.getDealerId()).getName());
                        }
                        if (ToolUtil.isNotEmpty(dispatchOrder)) {

                            sendGoodsOrderTask.setDealerLevel(levelService.getById(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                    .lambda().eq(DealerLevel::getSysUserId, userService.getById(dispatchOrder.getDealerId()).getDeptId())).getLevelId()).getLevelName());
                        }
                        sendGoodsOrderTask.setProcessInstanceId(task.getProcessInstanceId());
                        sendGoodsOrderTask.setTaskId(task.getId());
                        sendGoodsOrderTask.setCreateTime(sendGoods.getCreateTime());
                        return sendGoodsOrderTask;
                    }).collect(Collectors.toList());
            if (a.size() == 0) {
                b = tasks.stream().filter(task -> dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
                        .lambda().eq(DispatchOrder::getProcessInstanceId, task.getProcessInstanceId())) != null)
                        .filter(task -> areaIds.contains(getAreaId(task)))
                        .map(task -> {
                            SendGoodsOrderTask sendGoodsOrderTask = new SendGoodsOrderTask();
                            BeanUtils.copyProperties(dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
                                    .lambda().eq(DispatchOrder::getProcessInstanceId, task.getProcessInstanceId())), sendGoodsOrderTask);
                            if (ToolUtil.isNotEmpty(sendGoodsOrderTask.getDealerId())) {
                                sendGoodsOrderTask.setDealerName(userService.getById(sendGoodsOrderTask.getDealerId()).getName());
                            }
                            if (ToolUtil.isNotEmpty(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                    .lambda().eq(DealerLevel::getSysUserId, userService.getById(sendGoodsOrderTask.getDealerId()).getDeptId())))) {
                                sendGoodsOrderTask.setDealerLevel(levelService.getById(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                        .lambda().eq(DealerLevel::getSysUserId, userService.getById(sendGoodsOrderTask.getDealerId()).getDeptId())).getLevelId()).getLevelName());
                            }
                            sendGoodsOrderTask.setProcessInstanceId(task.getProcessInstanceId());
                            sendGoodsOrderTask.setTaskId(task.getId());
                            return sendGoodsOrderTask;
                        }).collect(Collectors.toList());
            }
            System.out.println(b);
            b.addAll(a);
            LayuiPageInfo result = new LayuiPageInfo();
            result.setCount(a.size());
            result.setData(b);
            return result;
        } else {
            return new LayuiPageInfo();
        }
//        }else {
//               indentOrderTasks =tasks.stream().filter(task -> dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
//                       .lambda().eq(DispatchOrder::getProcessInstanceId, task.getProcessInstanceId())) != null).map(task -> {
//                BeanUtils.copyProperties(dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
//                        .lambda().eq(DispatchOrder::getProcessInstanceId, task.getProcessInstanceId())), sendGoodsOrderTask);
//                if(ToolUtil.isNotEmpty(userService.getById(sendGoodsOrderTask.getDealerId()).getName())){
//                    sendGoodsOrderTask.setDealerName(userService.getById(sendGoodsOrderTask.getDealerId()).getName());
//                }if(ToolUtil.isNotEmpty(userService.getById(sendGoodsOrderTask.getDealerId()).getDeptId())){
//                       sendGoodsOrderTask.setDealerLevel(levelService.getById(dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
//                               .lambda().eq(DealerLevel::getSysUserId, userService.getById(sendGoodsOrderTask.getDealerId()).getDeptId())).getLevelId()).getLevelName());
//                   }
//                sendGoodsOrderTask.setProcessInstanceId(task.getProcessInstanceId());
//                sendGoodsOrderTask.setTaskId(task.getId());
//                return sendGoodsOrderTask;
//            }).collect(Collectors.toList());
//        }

    }

    /**
     * 审核
     *
     * @param indentOrderAuditParam
     * @return
     */
    @RequestMapping("/check")
    @ResponseBody
    public ResponseData check(IndentOrderAuditParam indentOrderAuditParam) {

        DispatchOrderAudit dispatchOrderAudit = new DispatchOrderAudit();
        dispatchOrderAudit.setDispatchOrderId(indentOrderAuditParam.getDispatchId());
        BeanUtils.copyProperties(indentOrderAuditParam, dispatchOrderAudit);
        dispatchOrderAudit.setUserId(ShiroKit.getUserNotNull().getId());

        Task task = taskService.createTaskQuery().taskId(indentOrderAuditParam.getTaskId()).singleResult();
        dispatchOrderAudit.setProcessInstanceId(task.getProcessInstanceId());
        dispatchOrderAudit.setAuditTime(new Date());
        dispatchOrderAuditService.save(dispatchOrderAudit);

        //启动流程
        Map<String, Object> map = new HashMap<>();
        map.put("status", indentOrderAuditParam.getAuditStatus());
        taskService.complete(task.getId(), map);
        return ResponseData.success();
    }


    /**
     * 退回
     *
     * @param checkDTO
     * @return
     */
    @RequestMapping("/back")
    @ResponseBody
    public ResponseData comBack(CheckDTO checkDTO) {
        dispathService.back(checkDTO);
        return ResponseData.success();
    }

    /**
     * 获取当前订单的区域id
     *
     * @param task
     * @return
     */
    public Long getAreaId(Task task) {

        if (ToolUtil.isNotEmpty(task)) {
            DispatchOrder dispatchOrder = dispatchOrderService.getOne(new QueryWrapper<DispatchOrder>()
                    .lambda().eq(DispatchOrder::getProcessInstanceId, task.getProcessInstanceId()));
            if (ToolUtil.isNotEmpty(dispatchOrder)) {
                User user = userService.getById(dispatchOrder.getDealerId());
                if (ToolUtil.isNotEmpty(user)) {
                    Dept dept = deptService.getById(user.getDeptId());
                    if (ToolUtil.isNotEmpty(dept)) {
                        DealerLevel dealerLevel = dealerLevelService.getOne(new QueryWrapper<DealerLevel>()
                                .lambda().eq(DealerLevel::getSysUserId, dept.getDeptId()));
                        if (ToolUtil.isNotEmpty(dealerLevel)) {
                            return dealerLevel.getAreaId();
                        }
                    }
                }
            }
        }
        return null;
    }
}


